'ui';

let date = new Date()
if (date.getUTCMonth() + 1 >= 8 && date.getDate() >= 30) {
	toast('请付款后使用')
	exit()
}

auto.setWindowFilter(function (window) {
	return window.title == '抖音短视频'
})
 
let isRunning = false
let storage = storages.create('dy')
// 搜索内容
let query = storage.get('query', '')
// 私信内容
let content = storage.get('content', '')
let rcv = null
ui.statusBarColor('#40a5f3')
ui.layout(
	<vertical>
		<appbar bg="#40a5f3">
			<toolbar title="dy私信(测试有效期 8.28)" />
		</appbar>
		<Switch
			gravity="right"
			id="autoService"
			text="无障碍服务"
			checked="{{auto.service != null}}"
			padding="8 8 8 8"
			textSize="15sp"
		/>

		<text text="搜索内容:" marginLeft="20" />
		<card
			w="*"
			h="80"
			margin="20 10 20 20"
			cardCornerRadius="5dp"
			cardBackgroundColor="#e3e3e3"
			cardElevation="0dp"
			gravity="center"
			foreground="?selectableItemBackground"
		>
			<input
				id="query"
				text="{{query}}"
				hint="搜索内容"
				marginBottom="-6"
				gravity="top|left"
				textSize="12sp"
			/>
		</card>

		<text text="私信内容:" marginLeft="20" />
		<card
			w="*"
			h="200"
			margin="20 10 20 20"
			cardCornerRadius="5dp"
			cardBackgroundColor="#e3e3e3"
			cardElevation="0dp"
			gravity="center"
			foreground="?selectableItemBackground"
		>
			<input
				id="content"
				text="{{content}}"
				hint="私信内容"
				marginBottom="-6"
				gravity="top|left"
				textSize="12sp"
			/>
		</card>
		<horizontal margin="10" w="auto" layout_gravity="center">
			<frame w="auto" layout_weight="1" h="auto" layout_gravity="center">
				<img
					h="*"
					src="#00000000"
					borderWidth="1dp"
					scaleType="fitXY"
					borderColor="#40a5f3"
					circle="true"
				/>
				<text
					id="start"
					h="auto"
					text="开始运行"
					padding="10"
					gravity="center"
					textSize="12sp"
					textColor="#40a5f3"
				/>
			</frame>
		</horizontal>
	</vertical>
) 

ui.content.addTextChangedListener({
	afterTextChanged: function (tv) {
		content = tv.toString().trim()
	},
})

ui.query.addTextChangedListener({
	afterTextChanged: function (tv) {
		query = tv.toString().trim()
	},
})

ui.autoService.on('check', function (checked) {
	// 用户勾选无障碍服务的选项时，跳转到页面让用户去开启
	if (checked && auto.service == null) {
		app.startActivity({
			action: 'android.settings.ACCESSIBILITY_SETTINGS',
		})
	}
	if (!checked && auto.service != null) {
		auto.service.disableSelf()
	}
})

// 当用户回到本界面时，resume事件会被触发
ui.emitter.on('resume', function () {
	// 此时根据无障碍服务的开启情况，同步开关的状态
	ui.autoService.checked = auto.service != null
})

ui.start.on('click', function () {
	//程序开始运行之前判断无障碍服务
	if (auto.service == null) {
		toast('请先开启无障碍服务！')
		return
	}
	if (isRunning) {
		isRunning = false
		threads.shutDownAll()
		ui.run(() => {
			ui.start.setText('开始运行')
		})
		return
	}
	isRunning = true
	storage.put('content', content)
	storage.put('query', query)
	ui.run(() => {
		ui.start.setText('停止运行')
	})

	threads.start(function () {
		toast('开始运行')
		app.launchApp('抖音短视频')
		let flag = text('首页').findOne(10000)
		if (!flag) { 
			toast('启动失败')
			return
		}
		console.log('启动成功')
		main()
	})
})


function main() {
	threads.start(function () {
		// 去弹窗
		while (true) {
			try {
				text('取消').findOne(1000).click()
			} catch (error) {}
	
			try {
				text('以后再说').findOne(1000).click()
			} catch (error) {}
		}
	})


	// 搜索按钮
	id('com.ss.android.ugc.aweme:id/bfq').findOne(1000).click()
	desc('热点榜').findOne(5000)
	sleep(5000)
	// 设置搜索文本
	className('android.widget.EditText').findOne(1000).setText(query)
	// 点击第一个搜索结果
	clickFirstResult()
	// 滑动列表寻找可评论按钮
	while (true) {
		// 列表滑动
		id('com.ss.android.ugc.aweme:id/d4p').findOne(3000).scrollForward()
		if (!id('cun').exists()) {
			// 列表滑动
			id('com.ss.android.ugc.aweme:id/d4p').findOne(3000).scrollForward()
			sleep(1000)
			continue
		}
		// 点击可评论按钮
		id('cun').findOne(1000).click()

		while (true) {
			if (text('暂时没有更多了').exists()) {
				break
			}
			if (text('剩余评论因未授权抖音短视频，暂不支持查看').exists()) {
				break
			}
			rcv = getRcv()
			let len = rcv.childCount()
			for (let i = 0; i < len; i++) {
				rcv = getRcv()
				// 点头像
				if (!clickUserImg(i)) {
					continue
				}
				// 点关注
				follow()

				// 私信
				sendMessage()

				// 返回
				while (!desc('表情').className('android.widget.ImageView').exists()) {
					back()
					sleep(2000)
				}
			}
			sleep(800)
			rcv.scrollForward()
			// 点赞
			// id('cv0').click()
			sleep(800)
		}

		back()
		sleep(1000)
	}
}

function clickFirstResult() {
	let grv = null
	while (true) {
		grv = className('androidx.recyclerview.widget.RecyclerView')
			.id('cyh')
			.visibleToUser()
			.findOnce()
		if (grv.childCount() >= 2) {
			break
		}
	}
	let gBounds = grv.child(0).bounds()
	click(gBounds.centerX(), gBounds.centerY())
}

function getRcv() {
	let rcvTmp = className('androidx.recyclerview.widget.RecyclerView')
		.id('exh')
		.findOne(1000)
	if (!rcvTmp) {
		rcvTmp = className('androidx.recyclerview.widget.RecyclerView')
			.id('d4p')
			.findOne(1000)
	}
	return rcvTmp
}

function clickUserImg(i) {
	try {
		let child = rcv.child(i).child(0)
		child.findOne(id('cv0')).click()
		if (child.className() != 'android.view.ViewGroup') {
			return false
		}
		let child2 = child.child(0)
		if (child2.className() != 'android.widget.FrameLayout') {
			return false
		}
		let cBounds = child2.bounds()
		let y = cBounds.centerY()
		if (y <= rcv.bounds().top + 3) {
			return false
		}
		if (y >= rcv.bounds().bottom - 3) {
			return false
		}
		click(cBounds.centerX(), y)
	} catch (error) {
		console.log(error)
		return false
	}
	return true
}

function follow() {
	for (let i = 0; i < 15; i++) {
		// 5s秒判断
		sleep(500)
		if (text('私信').exists()) {
			// 私信
			text('私信').findOne(1000).parent().parent().click()
			break
		}
		if (text('#  关注').exists()) {
			text('#  关注').findOne(1000).click()
		}
	}
}

function sendMessage() {
	className('android.widget.EditText').findOne(5000).setText(content)
	desc('发送').className('android.widget.ImageView').findOne(2000).click()
}
